package com.weiqiao.report.util;

import com.mongodb.client.model.Filters;
import com.weiqiao.utils.StringUtils;
import org.bson.conversions.Bson;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class DateUtil {
    /**
     * 获取当前日期20181122
     *
     * @return
     */
    public static String getCurrentDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        return df.format(new Date());
    }

    /**
     * 获取当前日期2018-11-22
     *
     * @return
     */
    public static String getCurrentDate2() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(new Date());
    }

    /**
     * 获取昨天日期2018-11-22
     *
     * @return
     */
    public static String getYesterdayDate() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        String format = new SimpleDateFormat("yyyy-MM-dd").format(time);
        return format;
    }

    public static long getYesterdayTime() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        long time = 0;
        try {
            String today = com.weiqiao.utils.DateUtil.format(cal.getTime(), "yyyy/MM/dd");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
            time = sf.parse(today).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static long getBeginDayOfWeek(Date date) {
        if (date == null) {
            return 0;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayofweek = cal.get(Calendar.DAY_OF_WEEK);
        if (dayofweek == 1) {
            dayofweek += 7;
        }
        cal.add(Calendar.DATE, 2 - dayofweek);
        return getDayStartTime(cal.getTime());
    }

    public static long getEndDayOfWeek(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(getBeginDayOfWeek(date));
        cal.add(Calendar.DAY_OF_WEEK, 6);
        Date weekEndSta = cal.getTime();
        return getDayEndTime(weekEndSta);
    }

    public static long getDayStartTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    // 获取某个日期的结束时间
    public static long getDayEndTime(Date d) {
        Calendar calendar = Calendar.getInstance();
        if (null != d) {
            calendar.setTime(d);
        }
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 23, 59, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    public static long getYesterdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.DATE, -1);
        return cal.getTime().getTime();
    }

    public static long getNextdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.DATE, 1);
        return cal.getTime().getTime();
    }

    /**
     * 获取日期后一天
     *
     * @return
     */
    public static String getTomdayDate(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH, 1);
        Date time = cal.getTime();
        String format = new SimpleDateFormat("yyyy-MM-dd").format(time);
        return format;
    }

    /**
     * 取当前日期到秒
     *
     * @return
     */
    public static String getCurrentDate2s() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
        return df.format(new Date());
    }

    /**
     * 取当前日期到秒
     *
     * @return
     */
    public static String getCurrentDate3s() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(new Date());
    }

    /**
     * 把日期格式转换为字符串
     *
     * @param date
     * @return
     */
    public static String getCurrentDate4s(Date date) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(date);
    }

    /**
     * 获取当前日期+1
     *
     * @return
     */
    public static String getTomorrowDate() {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        return String.valueOf(Integer.valueOf(df.format(new Date())) + 1);
    }

    /**
     * 获取当前日期字符串
     *
     * @return
     */
    public static String getCurrentDateString() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日");
        return df.format(new Date());
    }

    /**
     * 获取当前年
     *
     * @return
     */
    public static int getCurrentYear() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.YEAR);
    }

    /**
     * 获取当前月
     *
     * @return
     */
    public static int getCurrentMonth() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.MONTH);
    }

    /**
     * 获取当前日
     *
     * @return
     */
    public static int getCurrentDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.DATE);
    }

    /**
     * 获取当前时
     *
     * @return
     */
    public static int getCurrentHourOfDay() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取当前秒
     *
     * @return
     */
    public static String getCurrentSecondOfDay() {
        String second = "";
        Calendar cal = Calendar.getInstance();
        int num = cal.get(Calendar.SECOND);
        if (num < 10) {
            second = "0" + num;
        } else {
            second = "" + num;
        }
        return second;
    }

    /**
     * 切割标准时间
     *
     * @param time
     * @return
     */

    public static String subStandardTime(String time) {
        int idx = time.indexOf(".");
        if (idx > 0) {
            return time.substring(0, idx).replace("T", " ");
        }
        return null;
    }

    /**
     * 将时间戳转化为字符串
     *
     * @param showTime
     * @return
     */
    public static String formatTime2String(long showTime) {
        return formatTime2String(showTime, false);
    }

    public static String formatTime2String(long showTime, boolean haveYear) {
        String str = "";
        long distance = System.currentTimeMillis() / 1000 - showTime;
        if (distance < 300) {
            str = "刚刚";
        } else if (distance >= 300 && distance < 600) {
            str = "5分钟前";
        } else if (distance >= 600 && distance < 1200) {
            str = "10分钟前";
        } else if (distance >= 1200 && distance < 1800) {
            str = "20分钟前";
        } else if (distance >= 1800 && distance < 2700) {
            str = "半小时前";
        } else if (distance >= 2700) {
            Date date = new Date(showTime * 1000);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            str = formatDateTime(sdf.format(date), haveYear);
        }
        return str;
    }

    public static String formatDate2String(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (time == null) {
            return "未知";
        }
        try {
            long createTime = format.parse(time).getTime() / 1000;
            long currentTime = System.currentTimeMillis() / 1000;
            if (currentTime - createTime - 24 * 3600 > 0) { // 超出一天
                return (currentTime - createTime) / (24 * 3600) + "天前";
            } else {
                return (currentTime - createTime) / 3600 + "小时前";
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "未知";
    }

    public static String formatDateTime(String time, boolean haveYear) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (time == null) {
            return "";
        }
        Date date;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
            return "";
        }

        Calendar current = Calendar.getInstance();
        Calendar today = Calendar.getInstance();
        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH));
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        Calendar yesterday = Calendar.getInstance();
        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);

        current.setTime(date);
        if (current.after(today)) {
            return "今天 " + time.split(" ")[1];
        } else if (current.before(today) && current.after(yesterday)) {
            return "昨天 " + time.split(" ")[1];
        } else {
            if (haveYear) {
                int index = time.indexOf(" ");
                return time.substring(0, index);
            } else {
                int yearIndex = time.indexOf("-") + 1;
                int index = time.indexOf(" ");
                return time.substring(yearIndex, time.length()).substring(0, index);
            }
        }
    }

    /**
     * 小时换算到秒 例如：08:30
     *
     * @param time
     * @return
     */
    public static int string2Number(String time) {
        int n = 0;
        String[] temp = time.split(":");
        if (temp.length > 1) {
            n = Integer.valueOf(temp[0]) * 3600 + Integer.valueOf(temp[1]) * 60;
        }
        return n;
    }

    /**
     * 获取当前时间，只截取到小时到秒
     *
     * @return
     */
    public static int getCurrentTime() {
        Calendar cal = Calendar.getInstance();
        int h = cal.get(Calendar.HOUR_OF_DAY);
        int m = cal.get(Calendar.MINUTE);
        int s = h * 3600 + m * 60;
        return s;
    }

    /**
     * 指定日期的凌晨时间戳 例如：new Data() 现在时间的凌晨时间戳
     *
     * @return
     */
    public static long getMorningCurrentTime(long current) {
        long earlyMoring = 0;
        try {
            String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date(current));
            Date CurrentTime = new SimpleDateFormat("yyyy-MM-dd").parse(time);
            // 当天的凌晨
            earlyMoring = CurrentTime.getTime();
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return earlyMoring;
    }

    /**
     * 获取次日凌晨时间戳
     *
     * @param time 形如 2016-05-23 18:30
     * @return
     */
    public static long getNextMorning(String time) {
        long morning = 0;
        try {
            Date d1 = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(time);
            Calendar dd = Calendar.getInstance();// 定义日期实例
            dd.setTime(d1);
            dd.add(Calendar.DATE, 1);
            morning = getMorningCurrentTime(dd.getTime().getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return morning;
    }

    /**
     * 输入时间戳，转换为由年月组成时间戳 例如：System.currentTimeMillis() 当前时间的年月组成的时间戳
     *
     * @return
     */
    public static long getYearsCurrentTime(long current) {
        long earlyMoring = 0;
        try {

            String time = new SimpleDateFormat("yyyy-MM").format(new Date(current));
            Date CurrentTime = new SimpleDateFormat("yyyy-MM").parse(time);
            // 年月组成的时间戳
            earlyMoring = CurrentTime.getTime();
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return earlyMoring;
    }

    /**
     * 由指定日期月、日组成的时间戳 例如：System.currentTimeMillis() 当前时间的时间戳
     *
     * @param data 指定日期的时间戳
     * @return
     */
    public static long getMonthDayTime(long date) {

        long result = 0;
        try {
            String time = new SimpleDateFormat("MM-dd").format(new Date(date));
            Date CurrentTime = new SimpleDateFormat("MM-dd").parse(time);
            result = CurrentTime.getTime();
        } catch (ParseException e) {

            e.printStackTrace();
        }
        return result;
    }

    /**
     * 将date类型格式化返回string
     *
     * @param date
     * @param format
     * @return
     */
    public static String format(Date date, String format) {
        DateFormat df = new SimpleDateFormat(format);
        return df.format(date);
    }

    public static Date addDay(Date date, int day) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 2);
        return cal.getTime();
    }

    public static Date minusDay(Date date, int day) {
        return addDay(date, -day);
    }

    /**
     * 时间转时间戳
     *
     * @param date 形如：2016-05-23 18:30
     * @return
     */
    public static long getTime(String date) {
        long time = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            time = format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 获取自定义的时间戳，时间转时间戳
     *
     * @param date   时间 形如：2018-10-09 11:11
     * @param custom 时间格式 形如：yyyy-MM-dd HH:mm
     * @return
     */
    public static long getCustomCurr(String date, String custom) {
        long time = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat(custom);
            time = format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 时间转时间戳
     *
     * @param date 形如：2016-05-23
     * @return
     */
    public static long getYMdToTime(String date) {
        long time = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            time = format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 根据输入的年月 转换为时间戳
     *
     * @param date 输入的日期形如：2018-09
     * @return
     */
    public static long getYearsByYM(String date) {
        long time = 0;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
            time = format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 获取给定时间戳的凌晨时间
     *
     * @param current
     * @return
     */
    public static long getToday(long current) {
        long time = 0;
        try {
            String today = com.weiqiao.utils.DateUtil.format(new Date(current), "yyyy/MM/dd");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
            time = sf.parse(today).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static long getTodayEnd(long current) {
        long time = 0;
        try {
            String today = com.weiqiao.utils.DateUtil.format(new Date(current), "yyyy/MM/dd");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
            time = sf.parse(today).getTime();
            time += 24 * 60 * 60 * 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 获得某天的结束时间，即2012-01-01 23:59:59
     *
     * @return
     */
    public static Date getDayEndTime(long endTime) {
        Date now = new Date(endTime);
        SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            now = longSdf.parse(shortSdf.format(now) + " 23:59:59");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return now;
    }

    /**
     * 获取给定时间戳的月份
     *
     * @param current
     * @return
     */
    public static long getMonth(long current) {
        long time = 0;
        try {
            String today = com.weiqiao.utils.DateUtil.format(new Date(current), "yyyy/MM");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM");
            time = sf.parse(today).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 获取上月的时间戳
     *
     * @return
     */
    public static long getLastMonth() {
        long time = 0;
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date); // 设置为当前时间
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
        date = calendar.getTime();
        try {
            String today = com.weiqiao.utils.DateUtil.format(date, "yyyy/MM");
            SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM");
            time = sf.parse(today).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 返回当前时间与当前时间的23:59:59之间的差
     *
     * @param currentTime 当前时间戳
     * @return int
     */
    public static Integer getTimeDifference(long currentTime) {
        Date endTime = getDayEndTime(currentTime);
        return (int) ((endTime.getTime() - currentTime) / 1000);
    }

    /**
     * 获取输入时间戳的月-日 时：分转化的时间戳（MM-dd HH:mm）
     *
     * @param currentTimeMillis 输入时间
     * @return
     */
    public static long getMonthDay(long currentTimeMillis) {
        long time = 0;
        String millis = com.weiqiao.utils.DateUtil.format(new Date(currentTimeMillis), "MM-dd HH:mm");
        try {
            SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
            time = format.parse(millis).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * String转为13位时间戳
     *
     * @param date "yyyy-MM-dd HH:mm"
     * @return
     */
    public static String stringToTimestamp(String date, DateFormat format) {
        String timestamp = "";
        try {
            Date date1 = format.parse(date);
            timestamp = String.valueOf(date1.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            return "0";
        }
        return timestamp;
    }

    /**
     * 13位时间戳转为String "yyyy-MM-dd HH:mm"
     *
     * @param timestamp 13位时间戳
     * @return
     */
    public static String timestampToString(String timestamp) {
        if (!StringUtils.isLong(timestamp)) {
            return "";
        }
        long times = Long.parseLong(timestamp);
        String time = com.weiqiao.utils.DateUtil.format(new Date(times), "yyyy-MM-dd HH:mm");
        return time;
    }

    /**
     * 13位时间戳转为String "yyyy-MM-dd"
     *
     * @param timestamp 13位时间戳
     * @return
     */
    public static String timestampToString2(long timestamp) {
        String time = com.weiqiao.utils.DateUtil.format(new Date(timestamp), "yyyy-MM-dd");
        return time;
    }

    /**
     * 13位时间戳转为String "yyyy-MM"
     *
     * @param timestamp 13位时间戳
     * @return
     */
    public static String timestampToStringYearAndMonth(String timestamp) {
        long times = Long.parseLong(timestamp);
        String time = com.weiqiao.utils.DateUtil.format(new Date(times), "yyyy-MM");
        return time;
    }

    /**
     * 输入月份，往前推或往后推月份输出时间([2018-07, 2018-08, 2018-09, 2018-10, 2018-11, 2018-12])
     *
     * @param time  月份 形如 2018-1 或 2018-01
     * @param month 往前推的月份,6:往前推六个月到本月
     * @return
     */
    public static List<String> getYearAndMonthNext(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<String> list = new ArrayList<>();
        try {
            for (int i = -4; i < 2; i++) {
                Date date = sdf.parse(time);
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.add(Calendar.MONTH, i);
                list.add(sdf.format(c.getTime()));
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 输入月份，往前推或往后推月份输出时间([2018-07, 2018-08, 2018-09, 2018-10, 2018-11, 2018-12])
     *
     * @param time  月份 形如 2018-1 或 2018-01
     * @param month 往前推的月份,6:往前推六个月到本月
     * @return
     */
    public static List<String> getYearAndMonth(String time, int month) {
        long curr = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        List<String> list = new ArrayList<>();
        try {
            for (int i = 0; i < month; i++) {
                Date date = sdf.parse(time);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - (month - i - 1));
                Date updateDate2 = calendar.getTime();
                curr = updateDate2.getTime();
                String time2 = com.weiqiao.utils.DateUtil.format(new Date(curr), "yyyy-MM");
                list.add(time2);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取当前年月 如:2018-09
     *
     * @return
     */
    public static String getYearAndMonth() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        if (month < 10) {
            return year + "-0" + month;
        } else {
            return year + "-" + month;
        }

    }

    /**
     * 获取1年之后的时间戳(13位)
     *
     * @return
     */
    public static long getNextYear(long curr) {
        Date date = new Date(curr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1);
        calendar.add(Calendar.DATE, -1);
        return calendar.getTimeInMillis();
    }

    /**
     * 输入月份，往前推或往后推月份输出时间戳
     *
     * @param time  月份 形如 2018-1 或 2018-01
     * @param month -为往前推，正为往后推
     * @return
     */
    public static long getAdvanceDelayMonth(String time, int month) {
        long curr = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        try {
            Date date = sdf.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + month);
            Date updateDate2 = calendar.getTime();
            curr = updateDate2.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return curr;
    }

    // 渠道统计 Felix.hu Begin

    /**
     * 获取几天前或几天后零点对应的标准日期.
     *
     * @param day 大于0表示几天后，小于0表示几天前，0表示今天.
     * @return 零点对应的标准日期.
     */
    public static Date getBeginTimeOfDay(int day) {
        Calendar calendar = Calendar.getInstance();
        // 时间回退或向前都是基于今天
        Date date = new Date();

        calendar.setTime(date);
        calendar.add(Calendar.DATE, day);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 获取指定时间对应月的第一天零点对应的标准时间.
     *
     * @param time 如"2018-09"或"2018-09-01", 为空时返回当前月第一天零点对应的标准时间.
     * @param fmt  如"yyyy-MM"或"yyyy-MM-dd"
     * @return 参数指定月的第一天零点的标准日期或当前月的第一天零点的标准日期.
     */
    public static Date getBeginTimeOfMonth(String time, String fmt) {
        Calendar calendar = Calendar.getInstance();
        Date date = null;
        if (time == null || time.isEmpty()) {
            date = new Date();

        } else {
            if (fmt == null || fmt.isEmpty()) {
                fmt = "yyyy-MM";
            }

            DateFormat sdf = new SimpleDateFormat(fmt);
            try {
                date = sdf.parse(time);
            } catch (ParseException e) {
                date = new Date();
            }
        }
        calendar.setTime(date);

        // 参数指定月份的第一天，如2018-11-01 00:00:00
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 获取指定日期的下一个月的第一天零点对应的标准时间.
     *
     * @param date 日期. null时返回当前月下一个月的第一天零点对应的标准时间.
     * @return 指定日期下一个月的第一天零点对应的标准时间.
     */
    public static Date getBeginTimeOfNextMonth(Date date) {
        if (date == null) {
            date = new Date();
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        return calendar.getTime();
    }

    /**
     * 将字符串形式的时间戳转换成标准日期.
     *
     * @param timestamp 字符串形式的时间戳. null或空串时返回当前时间.
     * @return 时间戳对应的标准日期.
     */
    public static Date timestampToDate(String timestamp) {
        if (timestamp == null || timestamp.isEmpty()) {
            return new Date();
        }

        Date date = null;
        try {
            date = new Date(Long.parseLong(timestamp));
        } catch (NumberFormatException e) {
            // 如果时间格式异常，则取当前时间
            date = new Date();
        }

        return date;
    }
    // 渠道统计 Felix.hu End

    /* -------------------渠道日报表(WANGJIAN)-START----------------------- */

    /**
     * 根据时间戳,返回当天四点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static long TodayFourClock(long timestamp) {
        long today = getToday(timestamp);
        long todayFiveClock = today + 1000 * 60 * 60 * 16;
        return todayFiveClock;
    }

    /**
     * 根据时间戳,返回前一天四点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static long YesterdayFourClock(long timestamp) {
        long today = getToday(timestamp);
        long yesterdayFiveClock = today - 1000 * 60 * 60 * 8;
        return yesterdayFiveClock;
    }

    /**
     * 根据时间戳,返回当天五点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static long TodayFiveClock(long timestamp) {
        long today = getToday(timestamp);
        long todayFiveClock = today + 1000 * 60 * 60 * 17;
        return todayFiveClock;
    }

    /**
     * 根据日期(yy-MM-dd),返回当天四点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static String TodayFiveClockString(String date) {
        long today = getToday(getYMdToTime(date));
        long todayFiveClock = today + 1000 * 60 * 60 * 16;
        String time = com.weiqiao.utils.DateUtil.format(new Date(todayFiveClock), "yyyy-MM-dd");
        return time;
    }

    /**
     * 根据日期(yy-MM-dd),返回前一天四点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static String YesterdayFiveClockString(String date) {
        long today = getToday(getYMdToTime(date));
        long yesterdayFiveClock = today - 1000 * 60 * 60 * 8;
        String time = com.weiqiao.utils.DateUtil.format(new Date(yesterdayFiveClock), "yyyy-MM-dd");
        return time;
    }

    /* -------------------渠道日报表(WANGJIAN)-END----------------------- */
    public static void main(String[] args) throws ParseException {
        long today = getToday(System.currentTimeMillis());
        long todayFiveClock = today - 1000 * 60 * 60 * 7;
        System.out.println(todayFiveClock);
        // DateUtil.getAdvanceDelayMonth("2018-5", -5);

        // long month = getMonth(System.currentTimeMillis());
        // long today = getToday(System.currentTimeMillis());
        // String timea1 = DateUtil.format(new Date(System.currentTimeMillis()),
        // "yymmdd");
        /*
         * String timea2 = DateUtil.format(new
         * Date(Long.parseLong("1537356600000")), "yyyy/MM/dd HH:mm");
         * System.out.println(timea2);
         */
        // System.out.println(timea2);
        //
        // long lastmonth = getLastMonth();
        // String timea3 = DateUtil.format(new Date(lastmonth), "yyyy/MM/dd
        // HH:mm");
        // System.out.println(timea3);

        // long month = System.currentTimeMillis();
        // System.out.println(month);
        // String timea3 = DateUtil.format(new Date(month), "MM-dd HH:mm:ssss");
        // System.out.println(timea3);
        // try {
        //
        // SimpleDateFormat time = new SimpleDateFormat("MM-dd HH:mm:ssss");
        // long timeStart = time.parse(timea3).getTime();
        // System.out.println(timeStart);
        // String timea4 = DateUtil.format(new Date(timeStart), "MM-dd
        // HH:mm:ssss");
        // System.out.println(timea4);
        //
        //
        // } catch (ParseException e) {
        // e.printStackTrace();
        // }

        // System.out.println(getCurrentMonth());
        // try {
        //
        // SimpleDateFormat time = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        // long timeStart = time.parse("2018/01/16 20:00").getTime();
        // long date = Long.parseLong("1516111042000");
        // System.out.println(timeStart);
        // String timea = DateUtil.format(new Date(timeStart), "yyyy/MM/dd
        // HH:mm");
        // System.out.println(timea);
        //
        // } catch (ParseException e) {
        // e.printStackTrace();
        // }
        //
        // System.out.println(DateUtil.getCurrentDate2s());
        // System.out.println(DateUtil.getCurrentDay());
        // System.out.println(DateUtil.string2Number("08:30"));
        // System.out.println(DateUtil.getCurrentTime());
    }

    public static Bson getTimeQuery(String time_str, Bson filter, String query_field) {
        try {
            String start = time_str.split("~")[0];
            String end = time_str.split("~")[1];

            Date startdate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(start);
            Date enddate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(end);

            filter = Filters.and(filter, Filters.gte(query_field, String.valueOf(startdate.getTime())));
            filter = Filters.and(filter, Filters.lt(query_field, String.valueOf(enddate.getTime())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return filter;
    }

    public static long getLastWeekdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.DAY_OF_WEEK, -7);
        return cal.getTime().getTime();
    }

    public static long getNextWeekdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.DAY_OF_WEEK, 7);
        return cal.getTime().getTime();
    }

    public static long getLastYeardayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.YEAR, -1);
        return cal.getTime().getTime();
    }

    public static long getLastMonthdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.MONTH, -1);
        return cal.getTime().getTime();
    }

    public static long getNextMonthdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.MONTH, 1);
        return cal.getTime().getTime();
    }

    public static long getThirtydayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.DATE, -29);
        return cal.getTime().getTime();
    }

    public static long getTwelveDayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.WEEK_OF_YEAR, -11);
        return cal.getTime().getTime();
    }

    public static long getTwelveMonthdayTime(long time) {
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(time);
        cal.add(Calendar.MONTH, -11);
        return cal.getTime().getTime();
    }

    public static String getFormateTime(String time, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        if (!StringUtils.isLong(time)) {
            return "";
        }
        return sdf.format(new Date(Long.valueOf(time)));
    }

    public static String getNoonTime(long endTime) {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(endTime);
        long noon_time = getToday(c.getTime().getTime()) + 11 * 60 * 60 * 1000L;
        return String.valueOf(noon_time);
    }
}
